//
//  ZNWBStatusCell.swift
//  ZNWeibo
//
//  Created by FunctionMaker on 2017/8/22.
//  Copyright © 2017年 FunctionMaker. All rights reserved.
//

import UIKit

@objc protocol ZNWBStatusCellDelegate: NSObjectProtocol {
    // 如果需要设置可选协议方法，协议定义需要加@objc，方法需要加@objc optional
    @objc optional func statusCellDidSelectedURLString(cell: ZNWBStatusCell, urlString: String)
}

// 快速滚动时，帧率达到50+即表示滚动流畅

class ZNWBStatusCell: UITableViewCell {
    
    weak var delegate: ZNWBStatusCellDelegate?
    
    var model: ZNWBStatusViewModel? {
        didSet {
            nickNameLabel.text = model?.status.user?.screen_name
            contentLabel.attributedText = model?.statusAttrContent
            sourceLabel.text = model?.status.source
            
            vipView.image = model?.memberIcon
            avatarVipView.image = model?.vipIcon
            
            iconView.zn_setImage(urlString: model?.status.user?.profile_image_url,
                                 placeholderImage: #imageLiteral(resourceName: "avatar_default_big"),
                                 isAvatar: true)
            
            toolBar.viewModel = model
            
            picturesView.viewModel = model
            
            retweetedContentLabel?.attributedText = model?.retweetedAttrContent
        }
    }
    
    /// UILabel的渲染性能很差！具有混合图层！
    /// 头像
    @IBOutlet weak var iconView: UIImageView!
    /// vip
    @IBOutlet weak var vipView: UIImageView!
    /// 认证
    @IBOutlet weak var avatarVipView: UIImageView!
    
    /// 昵称
    @IBOutlet weak var nickNameLabel: UILabel!
    /// 时间
    @IBOutlet weak var timeLabel: UILabel!
    /// 来源
    @IBOutlet weak var sourceLabel: UILabel!
    /// 微博正文
    @IBOutlet weak var contentLabel: FFLabel!
    
    /// 对于原创微博，没有这个标签
    @IBOutlet weak var retweetedContentLabel: FFLabel?
        
    @IBOutlet weak var picturesView: ZNWBPicturesView!
    @IBOutlet weak var toolBar: ZNWBStatusToolBar!
    
    override func awakeFromNib() {
        super.awakeFromNib()
        
        // 高级优化，消耗CPU，耗电（CPU和GPU切换频繁）。如果Cell性能很好，就不需要离屏渲染
        // 离屏渲染，即异步绘制
        self.layer.drawsAsynchronously = true
        
        // 栅(shan)格化。异步绘制后，会生成一张独立的图像，cell在屏幕上滚动的时候，本质上滚动的是这张图片，即视图就只为这张图像。此时视图就只有一层
        // 在Cell停止滚动后，可以接受用户的交互
        self.layer.shouldRasterize = true
        
        // 栅格化后必须制定分辨率，否则视图显示效果很模糊
        self.layer.rasterizationScale = UIScreen.main.scale
        
        contentLabel.delegate = self
        retweetedContentLabel?.delegate = self
    }
}

extension ZNWBStatusCell: FFLabelDelegate {
    func labelDidSelectedLinkText(label: FFLabel, text: String) {
        if !text.hasPrefix("http://") {
            return
        }
        
        // 用可选？来替代OC中判断代理能否响应代理协议方法
        delegate?.statusCellDidSelectedURLString?(cell: self, urlString: text)
    }
}
